from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
from reportservice.helpers import ApiResponse
import json
from datetime import datetime
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
import os
import tempfile
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from doc_service.utils import merge_pdfs
from reportservice.helpers import ApiResponse
import json
from yida_app_service.utils.xmutils import convert_to_pdf
from yida_app_service.views import get_xm_client
from yida_app_service.xu_cloud_client import XmCloudBaseClient
from .yida_config import YidaClient
import requests
from oss_service.views import bucket
import pandas as pd
from io import BytesIO
import uuid
from .yida_config import YidaClient
from .yida_config import YidaClient

yida_client = YidaClient()
admin_user_id = "014835331124251186"
r = redis.StrictRedis(host='10.8.0.83', port=6379, db=0)
company_name = "zhongcheng"
    
@csrf_exempt
@require_http_methods(["GET"])
def prepare_price_shell(request):
    project_id = request.GET.get('project_id')
    project_info = yida_client.get_form_items_by_ids("FORM-CCDDFACAAF2B42CA9E471E9C9B13D8A84XCS",
                                      project_id,
                                      admin_user_id)
    if(project_info and project_info[0].form_data.get('attachmentField_lvhny282')):
        attachment = json.loads(project_info[0].form_data['attachmentField_lvhny282'])
        if(attachment):
            download_url = attachment[0].get("downloadUrl")
        else:
            return ApiResponse.fail("未找到价格清单")
        full_download_url = yida_client.get_full_download_url(admin_user_id, download_url)
        response = requests.get(full_download_url.body.result)
        if response.status_code == 200:
            price_shell_content = response.content
            excel_file = BytesIO(price_shell_content)
            df = pd.read_excel(excel_file)
            for index, row in df.iterrows():
                redis_key = f"{str(row['检测项目'])}-{str(row['检测参数'])}"
                redis_value = str(row['费用'])
                # 存储到Redis
                r.set(f"shunwei:{project_id}:{redis_key}", redis_value)
            return ApiResponse.success("success")
        else:
            return ApiResponse.fail("fail")
    else:
        return ApiResponse.fail("未找到价格清单")


@csrf_exempt
@require_http_methods(["GET"])
def get_single_price(request):
    project_id = request.GET.get('project_id')
    param_name = request.GET.get('param_name')
    param_key = rf"shunwei:{project_id}:{param_name}"
    price = r.get(param_key)
    if price:
        price = int(price.decode())
        return ApiResponse.success(price)
    else:
        return ApiResponse.fail("未找到价格")


@csrf_exempt
@require_http_methods(["POST"])
def gen_total_price(request):
    datasource: dict[str, any] = json.loads(request.body)
    project_id = datasource["project_id"]
    param_names = datasource['param_names']
    res_price = 0
    for param_name in param_names:
        param_key = rf"shujian:{project_id}:{param_name}"
        price = r.get(param_key)
        if price:
            price = int(price.decode())
            res_price = res_price + price
        else:
            ApiResponse.fail("未找到价格")
    return ApiResponse.success(res_price)


@csrf_exempt
@require_http_methods(["POST"])
def batch_print_report_statement(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids',[])
    form_uuid = "FORM-BA139B73C3AF479DA64C3D5EE991ED6B6ZE0"
    model_id = 159
    table_data = []
    render_data = {
        "结算数据":table_data
    }

    for form_inst_id in form_inst_ids:
        yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data:dict = yida_instance[0].form_data
        
        bg_info_str=form_data.get('associationFormField_lvw1b8w6_id')
        bg_info_detail=yida_client.get_associated_form_data(bg_info_str, admin_user_id)
        report_date_timestamp = bg_info_detail.get('dateField_lvhpww4i') #报告日期的毫秒时间戳
        if report_date_timestamp is not None:
            report_date = datetime.fromtimestamp(report_date_timestamp / 1000).strftime('%Y年%m月%d日')
        else:
            report_date = ''  # 报告日期

        wt_info_str = form_data.get('associationFormField_lvvrg0yz_id')
        wt_info_detail = yida_client.get_associated_form_data(wt_info_str, admin_user_id)
        project_name = wt_info_detail.get('textField_lvhw5i6u') #工程名称
        gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id') #关联工程
        gc_info_detail = yida_client.get_associated_form_data(gc_info_str, admin_user_id)
        entrust_unit = gc_info_detail.get('textField_lvhea612') #委托单位

        test_items = []  # 使用列表来收集参数
        test_project = wt_info_detail.get('selectField_lvhhb44k')  #检测项目
        if(wt_info_detail.get('radioField_lw8xidqm')=='常规'):
            test_parms_table = wt_info_detail.get('tableField_lvituc5q')
            unit = test_parms_table[0].get('selectField_lvj4hiij')  # 单位
    
            for test_parm in test_parms_table:
                item = test_parm.get('selectField_lwik49tr')
                if item:  
                    test_items.append(item)
    
            test_items = '、'.join(test_items)

        count =1 #数量
        report_info_str = form_data.get('associationFormField_lvw1b8w6_id')
        report_info_detail = yida_client.get_associated_form_data(report_info_str, admin_user_id)
        report_number = report_info_detail.get('textField_lvksipo5') #报告编号
        unit_price = float(wt_info_detail.get('numberField_lvkpm5tz')) #单价
        total_price = unit_price  #检测费
        table_data.append([report_date,entrust_unit,project_name,test_project,test_items,unit,count,report_number,unit_price,total_price])
    
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result_render = xm_client.render_model_xlsx(model_id,render_data)
    if result_render.get("code") == 200:
        res_data = result_render.get("data")
        result_url =xm_client.gen_detection_record_url(res_data.get("id"))
        if result_url.get("code") == 200:
            res = result_url.get("data")
            return ApiResponse.success(res.get("preview_url"))


@csrf_exempt
@require_http_methods(["GET"])
def get_full_report(request):
    form_uuid = "FORM-F57DFE3189CB44A0942F9F51D9BFAB47K9SP"
    form_inst_id = request.GET.get('formInstId')
    model_id = request.GET.get('model_id')
    # 获取表单数据
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
    if not yida_instance:
        return ApiResponse.fail(message="未找到相关表单数据")
    
    form_data:dict = yida_instance[0].form_data

    # 获取封面数据
    render_data = get_render_data(form_data)

    # 调用渲染服务
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.render_model(model_id,render_data)

    if result.get("code") != 200:
        return ApiResponse.fail(message="封面渲染失败")

    # 获取封面下载URL
    res_data = result.get("data")
    url_res = xm_client.gen_detection_record_url(res_data.get("id"))

    if url_res.get("code") != 200:
        return ApiResponse.fail(message="未找到报告生成记录")
    
    yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
    "attachmentField_lwed3j50":[
        {
        "downloadUrl": url_res.get("data").get("download_url"),
        "name": "报告封面.docx",
        "previewUrl": url_res.get("data").get("preview_url"),
        "url": url_res.get("data").get("preview_url"),
        "ext": "docx"
        }
    ]})
    # 获取封面和内容文件URL
    cover_url = url_res.get("data").get("download_url")
    form_data:dict = yida_instance[0].form_data
    content_info = json.loads(form_data["attachmentField_lvhrt9vg"])[0]
    content_url = content_info.get("downloadUrl")
    content_name = content_info.get("name")

    full_download_url = yida_client.get_full_download_url(admin_user_id,content_url)

    # 下载和转换PDF
    temp_dir = tempfile.mkdtemp()
    convert_and_download(cover_url, temp_dir, "cover.pdf")
    #内容文件下载
    response = requests.get(full_download_url.body.result)
    ext = content_name.split(".")[-1]
    if response.status_code == 200:
        content_content = response.content
        temp_content_path = os.path.join(temp_dir, f"content.{ext}")
        print(f"内容文件已存入缓存文件：{temp_content_path}")
        with open(temp_content_path, 'wb') as temp_file:
            temp_file.write(content_content)
        if ext == "xlsx" or ext == "docx":
            convert_to_pdf(temp_content_path,temp_dir)
            temp_content_path = os.path.join(temp_dir, f"content.pdf")

    # 构建PDF文件的路径
    cover_pdf = os.path.join(temp_dir, f"cover.pdf")
    content_pdf = os.path.join(temp_dir, f"content.pdf")
    # 合并PDF
    out_path = os.path.join(temp_dir, f"whole.pdf")
    merge_pdfs([cover_pdf, content_pdf], out_path)

    # 上传PDF到OSS
    oss_pdf_key = f"yida-app/{company_name}/{form_uuid}/{form_inst_id}/完整报告.pdf"
    bucket.put_object_from_file(oss_pdf_key, out_path)
    out_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_pdf_key}"

    # 更新宜搭表单
    update_yida_full_report(form_uuid,form_inst_id,out_url,oss_pdf_key)

    return ApiResponse.success(message='成功获取完整报告',data=out_url)

def update_yida_full_report(form_uuid,form_inst_id,out_url,oss_key):
    '''更新宜搭的完整报告附件的组件'''

    yida_client.update_form_data_by_id(form_uuid, admin_user_id, form_inst_id, {
    "attachmentField_lwf41dza": [{
        "downloadUrl": out_url,
        "name": "完整报告.pdf",
        "previewUrl": out_url,
        "url": out_url,
        "oss_key":oss_key,
        "ext": "pdf"
    }],
    "textField_lwrvb5wq":oss_key
})

def get_render_data(form_data):
    '''准备封面数据'''
    report_number = form_data.get('textField_lvksipo5') #报告编号
    wt_info_str = form_data.get('associationFormField_lvj6iq1p_id')
    wt_info_detail = yida_client.get_associated_form_data(wt_info_str,admin_user_id)
    test_item = wt_info_detail.get('selectField_lvhhb44k') #检测项目
    gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id')
    gc_info_detail = yida_client.get_associated_form_data(gc_info_str,admin_user_id)
    entrust_unit = gc_info_detail.get('textField_lvhea612')#委托单位
    contract_id = gc_info_detail.get('textField_lvhea60s') #合同编号
    project_name = wt_info_detail.get('textField_lvhw5i6u')#工程名称
    test_category = wt_info_detail.get('selectField_lvhg6k0l') #检测类别
    example_id = wt_info_detail.get('textField_lvhpww3f')
    js_unit = entrust_unit #建设单位
    jl_unit = gc_info_detail.get('textField_lvhea62s') #监理单位
    sg_unit = gc_info_detail.get('textField_lvhea628') #施工单位
    project_bw = gc_info_detail.get('textField_lwj204x0') #工程部位/规格型号
    design_unit = gc_info_detail.get('textField_lwk4ncbp') #设计单位
    project_addr = gc_info_detail.get('selectField_lvhea61j')#工程地址
    jzr_name = gc_info_detail.get('textField_lvhea62z')#见证人
    entrust_date_stmap = wt_info_detail.get('dateField_lw4oxok2') #受理日期
    date_range = form_data.get('cascadeDateField_lvhpww4h')
    if date_range: 
        jc_date_stamp = int(date_range[0]) #检测日期

    jc_category = wt_info_detail.get('radioField_lw8xidqm')
    test_items = []  # 检测参数：数量
    test_standards=[]
    if(jc_category=='常规'):
        test_parms_table = wt_info_detail.get('tableField_lvituc5q')
        for test_parm in test_parms_table:
            item = test_parm.get("selectField_lvituc5r","")+":"+str(test_parm.get('numberField_lvituc5s',0))
            standard = test_parm.get('textField_lx9ssfuj','') 
            if item:  
                test_items.append(item)
                test_standards.append(standard)
    elif(jc_category=='地基'):
        test_parms_table = wt_info_detail.get('tableField_lw8n0thp')
        for test_parm in test_parms_table:
            item = test_parm.get('selectField_lw8n0thk') + ":"+ str(test_parm.get('numberField_lw8n0thl'))
            standard = test_parm.get('textField_lx9ssful','') 
            if item:  
                test_items.append(item)
                test_standards.append(standard)
    elif(jc_category=='结构实体'):
        test_parms_table = wt_info_detail.get('tableField_lw8xidr2')
        for test_parm in test_parms_table:
            item = test_parm.get('selectField_lw8xidqx') +":"+ str(test_parm.get('numberField_lw8xidqy'))
            standard = test_parm.get('textField_lx9ssfun','')
            if item:  
                test_items.append(item)
                test_standards.append(standard)

    test_items = '、'.join(test_items)        
    test_standards = '、'.join(test_standards)  #检测标准
    example_name = wt_info_detail.get('textareaField_lvhpww36') #样品名称
    jcr_sign_url = form_data.get('digitalSignatureField_lwed3j4v') #检测人签名1
    shr_sign_url = form_data.get('digitalSignatureField_lwinoatx') #审核人签名
    pzr_sign_url = form_data.get('digitalSignatureField_lwinoaty') #批准人签名
    pzr_name = form_data.get('selectField_lwkc2qg8') #批准人名字
    shr_name = form_data.get('selectField_lwkc2qg7') #审核人名字
    ass_jcr :list = json.loads(json.loads(form_data.get('associationFormField_lwu19i9t_id')))
    titles = [obj['title'] for obj in ass_jcr] #检测人名字
    jcr_names = '、'.join(titles) #检测人名字
    qf_date = datetime.now().timestamp() #签发日期
    render_data = {
    "报告编号": report_number,
    "样品编号":example_id,
    "检测项目": test_item,
    "项目名称":test_item,
    "工程名称": project_name,
    "委托单位": entrust_unit,
    "合同编号": contract_id,
    "检测类别": test_category,
    "建设单位": js_unit,
    "监理单位": jl_unit,
    "施工单位": sg_unit,
    "规格型号": project_bw,
    "设计单位": design_unit,
    "工程地址": project_addr,
    "见证人": jzr_name,
    "受理日期": entrust_date_stmap,
    "检测日期": jc_date_stamp,
    "检测参数及数量": test_items,
    "样品名称": example_name,
    #"审核人签名": shr_sign_url,
   # "批准人签名": pzr_sign_url,
    #"检测人签名1": jcr_sign_url,
    "批准人": pzr_name,
    "审核人": shr_name,
    "检测人1": jcr_names,
    "签发日期":qf_date,
    "检测依据":test_standards
    }
    return render_data


def convert_and_download(url, output_dir, filename):
    response = requests.get(url)
    if response.status_code == 200:
        file_path = os.path.join(output_dir, filename)
        with open(file_path, 'wb') as file:
            file.write(response.content)
        convert_to_pdf(file_path, output_dir)  # 执行PDF转换
    else:
        raise Exception("Failed to download or convert file")

@csrf_exempt
@require_http_methods(['POST'])
def print_report_file(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids',[])
    form_uuid = "FORM-F57DFE3189CB44A0942F9F51D9BFAB47K9SP"
    reports_pdf_paths=[]
    if len(form_inst_ids):
        temp_dir = tempfile.mkdtemp()
        for form_inst_id in form_inst_ids:
            yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
            form_data:dict = yida_instance[0].form_data
            report_file_url = json.loads(form_data["attachmentField_lwf41dza"])[0].get("downloadUrl")
            # 下载完整报告
            with requests.Session() as session:  # 使用 requests 库创建一个会话对象，用于发送 HTTP 请求。
                response = session.get(report_file_url)  # 发送 GET 请求以获取文件内容。
                if response.status_code == 200:
                    report_content = response.content
                    temp_report_path = os.path.join(temp_dir, f"{form_inst_id}.pdf")
                    print(f"完整报告文件已存入缓存文件：{temp_report_path}")
                    with open(temp_report_path, 'wb') as temp_file:
                        temp_file.write(report_content)
                    reports_pdf_paths.append(temp_report_path)
        
        out_path = os.path.join(temp_dir, "AllReports.pdf")
        merge_pdfs(reports_pdf_paths,out_path)                
        oss_pdf_key = f"yida-app/{company_name}/{form_uuid}/报告{uuid.uuid4()}.pdf"
        bucket.put_object_from_file(oss_pdf_key,out_path)
        out_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_pdf_key}"
        return ApiResponse.success(data=out_url,message='报告打印成功')
    return ApiResponse.fail('报告打印失败')

@csrf_exempt
@require_http_methods(["POST"])
def batch_print_yplzd(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids')
    form_uuid = "FORM-951C75BA36E147909E9E56E1A60035447ACY"
    model_id = 161
    table_data = []
    render_data = {
        "打印时间":datetime.now().timestamp(),
        "表格内容":table_data
    }
    for index,form_inst_id in enumerate(form_inst_ids):
        yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data:dict = yida_instance[0].form_data
        wtrq = datetime.fromtimestamp(form_data["dateField_lw4oxok2"]/1000).strftime("%Y-%m-%d")
        jcdm = "" #监测代码
        ypmc = form_data["textareaField_lvhpww36"]
        ypbh = form_data["textField_lvhpww3f"]
        slr = form_data["employeeField_lvuo2hz7"][0]
        jsr = "" #接收人
        jsrq = "" #接受日期
        ypcz = "" #样品处置
        bz = form_data["textField_lw6b30qv"] #备注
        table_data.append([index+1,wtrq,jcdm,ypmc,ypbh,slr,jsr,jsrq,ypcz,bz])
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result_render = xm_client.render_model_xlsx(model_id,render_data)
    if result_render.get("code") == 200:
        res_data = result_render.get("data")
        result_url =xm_client.gen_detection_record_url(res_data.get("id"))
        if result_url.get("code") == 200:
            res = result_url.get("data")
            return ApiResponse.success(res.get("preview_url"))      

@csrf_exempt
@require_http_methods(["GET"])
def sign_name_to_full_report(request):
    form_inst_id = request.GET.get('formInstId')
    form_uuid = "FORM-F57DFE3189CB44A0942F9F51D9BFAB47K9SP"
    model_id = request.GET.get('model_id')
    # 获取表单数据
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
    if not yida_instance:
        return ApiResponse.fail(message="未找到相关表单数据")
    
    form_data:dict = yida_instance[0].form_data
    
    #签名获取
    tester_signature_url_1 = form_data.get('digitalSignatureField_lwed3j4v')
    tester_signature_url_2 = ''
    reviewer_signature_url = form_data.get('digitalSignatureField_lwinoatx')
    approver_signature_url = form_data.get('digitalSignatureField_lwinoaty')
    sign_data = {"检测人签名1":tester_signature_url_1,"检测人签名2":tester_signature_url_2,
                 "审核人签名":reviewer_signature_url,"批准人签名":approver_signature_url}
    oss_key = form_data.get('textField_lwrvb5wq')
    pdf_info = {"oss_key":oss_key}
    sign_data_parms = {"sign_data":sign_data,"pdf_info":pdf_info}

    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.sign_to_pdf_file(model_id,sign_data_parms)
    if result.get("code") == 200:
        return ApiResponse.success(message='签名成功')
    return ApiResponse.fail('签名失败')


@csrf_exempt
@require_http_methods(["GET"])
def batch_print_jsd(request):
    formInstId = request.GET.get('formInstId')
    form_uuid = "FORM-B34C051E9579498A92E98C36C308C0F3YTWK"
    model_id = 159
    yida_instance = yida_client.get_form_items_by_ids(form_uuid,formInstId,admin_user_id)
    form_data_be:dict = yida_instance[0].form_data
    priced_info_str = form_data_be.get('associationFormField_lvkva1eh_id')
    form_inst_ids = []
    if priced_info_str:
        priced_info_list = json.loads(json.loads(priced_info_str))
        for priced_info in priced_info_list:
            form_inst_ids.append(priced_info.get('instanceId'))
        if form_inst_ids:
            table_data = []
            render_data = {
                "结算数据":table_data
            }

            for form_inst_id in form_inst_ids:
                yida_instance = yida_client.get_form_items_by_ids("FORM-BA139B73C3AF479DA64C3D5EE991ED6B6ZE0",form_inst_id,admin_user_id)
                form_data:dict = yida_instance[0].form_data
                
                bg_info_str=form_data.get('associationFormField_lvw1b8w6_id')
                bg_info_detail=yida_client.get_associated_form_data(bg_info_str, admin_user_id)
                report_date_timestamp = bg_info_detail.get('dateField_lvhpww4i') #报告日期的毫秒时间戳
                if report_date_timestamp is not None:
                    report_date = datetime.fromtimestamp(report_date_timestamp / 1000).strftime('%Y年%m月%d日')
                else:
                    report_date = ''  # 报告日期

                wt_info_str = form_data.get('associationFormField_lvvrg0yz_id')
                wt_info_detail = yida_client.get_associated_form_data(wt_info_str, admin_user_id)
                project_name = wt_info_detail.get('textField_lvhw5i6u') #工程名称
                gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id') #关联工程
                gc_info_detail = yida_client.get_associated_form_data(gc_info_str, admin_user_id)
                entrust_unit = gc_info_detail.get('textField_lvhea612') #委托单位

                test_items = []  # 使用列表来收集参数
                test_project = wt_info_detail.get('selectField_lvhhb44k')  #检测项目
                if(wt_info_detail.get('radioField_lw8xidqm')=='常规'):
                    test_parms_table = wt_info_detail.get('tableField_lvituc5q')
                    unit = test_parms_table[0].get('selectField_lvj4hiij')  # 单位
            
                    for test_parm in test_parms_table:
                        item = test_parm.get('selectField_lwik49tr')
                        if item:  
                            test_items.append(item)
            
                    test_items = '、'.join(test_items)

                count =1 #数量
                report_info_str = form_data.get('associationFormField_lvw1b8w6_id')
                report_info_detail = yida_client.get_associated_form_data(report_info_str, admin_user_id)
                report_number = report_info_detail.get('textField_lvksipo5') #报告编号
                unit_price = float(wt_info_detail.get('numberField_lvkpm5tz')) #单价
                total_price = unit_price  #检测费
                table_data.append([report_date,entrust_unit,project_name,test_project,test_items,unit,count,report_number,unit_price,total_price])
            
            XmCloudClient = get_xm_client(company_name)
            xm_client:XmCloudBaseClient = XmCloudClient()
            result_render = xm_client.render_model_xlsx(model_id,render_data)
            if result_render.get("code") == 200:
                res_data = result_render.get("data")
                result_url =xm_client.gen_detection_record_url(res_data.get("id"))
                if result_url.get("code") == 200:
                    res = result_url.get("data")
                    yida_client.update_form_data_by_id(form_uuid, admin_user_id, formInstId, {
                        "attachmentField_lwsvad6v": [{
                            "downloadUrl": res.get("download_url"),
                            "name": "电子结算单.pdf",
                            "previewUrl": res.get("preview_url"),
                            "url": res.get("download_url"),
                            "ext": "pdf"
                        }]
                    })
                    return ApiResponse.success(res.get("preview_url"))    